<?php $this->load->view('templates/backend/header'); ?>
<h3><?php echo $this->lang->line("voucher_list");?></h3>

<style>
.num_cls{
    width:15%;
}
.btn-success,.btn-danger{
    vertical-align: top;
}
.notice{
    color:green;
}
</style>

<?php if (isset($flash_message)  && $flash_message!=NULL ): ?>
<div class="alert alert-success"><a class="close" customerAssess-dismiss="alert">x</a><strong><?php echo $flash_message; ?></strong></div>
<?php endif; ?>
<div class="well">
    <?php echo form_open();?>
        <div class="tab-content">	
            <div class="tab-pane active" id="main">
                <?php
                //thông tin khách hàng
                echo form_label($this->lang->line('phone'), 'phone');
                echo form_input(array('name' => 'phone', 'id' => 'phone', 'value' => ($voucher->phone)?$voucher->phone:'','required'=>'required','class'=>'num_cls','placeholder'=>$this->lang->line('phone'),'class'=>'num_cls'));
                echo form_error('phone');
                
                if ($this->uri->segment(4) == "add"){
                        echo ' <span id="findCustomer"></span>';
                        //action add
                        echo '<div id="foneadd">';//begin id foneadd
                        echo '<div id="fone_addon1" class="fonediv">';
                        //Loại booking
                        echo form_label($this->lang->line('voucher_info'), 'booking_types');
                        echo form_dropdown('booking_types[]', $this->voucher_model->getListBookingTypes(), '1','id="booking_types1" class="num_cls" disabled="disabled"');
                        echo form_error('booking_types');
                        echo ' ';
                        //hãng
                        echo form_input(array('readonly' => 'true','name' => 'airline[]', 'id' => 'airline1', 'value' => '','required'=>'required','maxlength'=>'2','class'=>'num_cls','placeholder'=>$this->lang->line('airline')));
                        echo form_error('airline');
                        echo ' ';
                        //code
                        echo form_input(array('readonly' => 'true','name' => 'booking_place_code[]', 'id' => 'booking_place_code1', 'value' => '','required'=>'required','class'=>'num_cls','placeholder'=>$this->lang->line('booking_place_code')));
                        echo form_error('booking_place_code');
                        echo ' ';
                        //ngay dat
                        echo form_input(array('type' => 'hidden','name' => 'createdTime[]', 'id' => 'createdTime1', 'value' => ''));
                        //Giá net
                        echo form_input(array('name' => 'net_fare[]', 'id' => 'net_fare1', 'value' => '','readonly' => 'true','required'=>'required','class'=>'num_cls','placeholder'=>$this->lang->line('net_fare')));
                        echo form_error('net_fare');
                        echo form_input(array('type' => 'hidden','name' => 'net_fare_fake[]', 'id' => 'net_fare_fake1', 'value' => '','class'=>'sumNet'));
                        echo ' ';
                        //Giá bán
                        echo form_input(array('name' => 'sale_fare[]', 'id' => 'sale_fare1', 'value' => '','readonly' => 'true','required'=>'required','class'=>'num_cls','placeholder'=>$this->lang->line('sale_fare')));
                        echo form_error('sale_fare');
                        echo form_input(array('type' => 'hidden','name' => 'sale_fare_fake[]', 'id' => 'sale_fare_fake1', 'value' => '','class'=>'sumSale'));
                        echo ' ';
                        echo form_button(array('adata' => 1,'content' => $this->lang->line('add'),'class' => 'btn btn-success'));
                        echo '<span id="simple-msg-phone1"></span>';
                        echo '</div></div>';//end id foneadd
                } else {
                    //mã đặt chỗ
                    echo form_label($this->lang->line('voucher_info'), 'booking_types');
                    echo '<div id="foneadd">';//begin id foneadd
                    foreach($voucher->booking_info as $keys => $vals){
                        $keys += 1;
                        //action add
                        echo '<div id="fone_addon'.$keys.'" class="fonediv">';
                        //Loại booking
                        echo form_dropdown('booking_types[]', $this->voucher_model->getListBookingTypes(), $vals['booking_types'],'id="booking_types'.$keys.'" class="num_cls" readonly="true"');
                        echo form_error('booking_types');
                        echo ' ';
                        //hãng
                        echo form_input(array('readonly' => 'true','name' => 'airline[]', 'id' => 'airline'.$keys, 'value' => $vals['airline'],'required'=>'required','maxlength'=>'2','class'=>'num_cls','placeholder'=>$this->lang->line('airline')));
                        echo form_error('airline');
                        echo ' ';
                        //code
                        echo form_input(array('readonly' => 'true','name' => 'booking_place_code[]', 'id' => 'booking_place_code'.$keys, 'value' => $vals['booking_place_code'],'required'=>'required','class'=>'num_cls','placeholder'=>$this->lang->line('booking_place_code')));
                        echo form_error('booking_place_code');
                        echo ' ';
                        //ngay dat
                        echo form_input(array('type' => 'hidden','name' => 'createdTime[]', 'id' => 'createdTime'.$keys, 'value' => $vals['createdTime']));
                        //Giá net
                        echo form_input(array('readonly' => 'true','name' => 'net_fare[]', 'id' => 'net_fare'.$keys, 'value' => $vals['net_fake'],'required'=>'required','class'=>'num_cls','placeholder'=>$this->lang->line('net_fare')));
                        echo form_error('net_fare');
                        echo form_input(array('type' => 'hidden','name' => 'net_fare_fake[]', 'id' => 'net_fare_fake'.$keys, 'value' => $vals['net'],'class'=>'sumNet'));
                        echo ' ';
                        //Giá bán
                        echo form_input(array('readonly' => 'true','name' => 'sale_fare[]', 'id' => 'sale_fare'.$keys, 'value' => $vals['sale_fake'],'required'=>'required','class'=>'num_cls','placeholder'=>$this->lang->line('sale_fare')));
                        echo form_error('sale_fare');
                        echo form_input(array('type' => 'hidden','name' => 'sale_fare_fake[]', 'id' => 'sale_fare_fake'.$keys, 'value' => $vals['sale'],'class'=>'sumSale'));
                        if($keys==1){
                            echo ' ';
                            echo form_button(array('adata' => $keys,'content' => $this->lang->line('add'),'class' => 'btn btn-success'));
                        }
                        if($keys==2){
                            echo ' ';
                            echo form_button(array('value' => $keys,'adata' => $keys,'content' => $this->lang->line('delete'),'class' => 'btn btn-danger','onclick'=>'deleteRecord(this)'));
                        }
                        echo '<span id="simple-msg-phone'.$keys.'"></span>';
                        echo '</div>';//end id foneadd
                    }
                    echo '</div>';
                    echo form_input(array('type' => 'hidden','name' => 'customerID', 'id' => 'customerID', 'value' => ($voucher->customerID)?$voucher->customerID:''));
                }
                
                echo form_input(array('type' => 'hidden','name' => 'payment_method_fake', 'id' => 'payment_method_fake', 'value' => ($voucher->payment_method)?$voucher->payment_method:''));
                
                // Tong net
                echo form_label($this->lang->line('sumNet'), 'sumNet');
                echo form_input(array('name' => 'sumNet', 'id' => 'sumNet', 'readonly' => 'true','value' => ($voucher->net_fare)?$voucher->net_fare:'','placeholder'=>$this->lang->line('sumNet')));
                echo form_input(array('type' => 'hidden','name' => 'sumNet_fake', 'id' => 'sumNet_fake', 'value' => ($voucher->net_fare)?$voucher->net_fare:''));
                echo form_error('sumNet');
                 // Tong gia ban
                echo form_label($this->lang->line('sumSale'), 'sumSale');
                echo form_input(array('name' => 'sumSale', 'id' => 'sumSale', 'readonly' => 'true','value' => ($voucher->sale_fare)?$voucher->sale_fare:'','placeholder'=>$this->lang->line('sumSale')));
                echo form_input(array('type' => 'hidden','name' => 'sumSale_fake', 'id' => 'sumSale_fake', 'value' => ($voucher->sale_fare)?$voucher->sale_fare:''));
                echo form_error('sumSale');
                //Phương thức thanh toán
                echo form_label($this->lang->line('payment_method').' <span class="required">*</span>', 'payment_method');
                echo form_dropdown('payment_method', $this->voucher_model->getListPaymentMethod(), ($voucher->payment_method)?$voucher->payment_method:'','id="payment_method" disabled="disabled"');
                echo form_error('payment_method');
                echo '<span id="payment_method_form"></span>';
                //Ghi chú
                echo form_label($this->lang->line('note_bk'), 'note_bk');
                echo form_textarea(array('name' => 'note_bk', 'id' => 'note_bk', 'value' => ($voucher->note_bk)?$voucher->note_bk:'','rows'=>'5','readonly' => 'true'));
                echo form_error('note_bk');
                ?>
            </div>
        </div>
        <div class="top-button">
                <?php echo form_button(array('id' => 'submit', 'value' => 'Update', 'name' => 'submit', 'type' => 'submit', 'content' => $this->lang->line('save'),'class' => 'btn btn-primary')); ?>
                <a href="<?php echo site_url('auth/voucher'); ?>" class="btn btn-danger"><?php echo $this->lang->line('cancel')?></a>
        </div>
    <?php form_close();?>
    <span id="simple-msg-submit"></span>
</div>

<?php $this->load->view('templates/backend/footer'); ?>
<?php $this->load->view('templates/backend/lib'); ?>

<script src="<?php echo base_url().'static/templates/backend/js/autoNumeric.js';?>"></script>
<script type="text/javascript">    
    $(document).ready(function() {
            var url_segment = '<?php echo $this->uri->segment(4);?>';
            if(url_segment == 'edit'){
                $("#phone").attr('readonly','true');
                $('#payment_method').removeAttr('disabled');
            } else {
                $('button[type="submit"]').attr('disabled','disabled');
                $('button[type="button"]').attr('disabled','disabled');    
            }
            
            $("#phone").blur(function() {
                    var sodt        = $("#phone").val().trim();
                    var test        = /^[0-9]+$/.test(sodt);
                    if(test == false){
                        alert("<?php echo $this->lang->line('phone_is_invalid');?>");
                        return false;
                    }
                    if(sodt.length < 10){
                        alert("Số dt phải có ít nhất 10 số!");return false;
                    } else {
                        var formURL     = '/auth/voucher/getContactFromPhone';
                        setTimeout(function () {
                            $.ajax(
                                    {
                                            url : formURL,
                                            type: "POST",
                                            data : {phone:$("#phone").val()},
                                            cache: true,
                                            success:function(responseData) 
                                            {
                                                if(responseData == 0){
                                                    alert("<?php echo $this->lang->line("customerNotFound");?>");
                                                    $("#findCustomer").hide();
                                                    $("#phone").focus();return false;
                                                } else {
                                                    var data    = JSON.parse(responseData);
                                                    $("#findCustomer").html('<span class="notice">SĐT hợp lệ - Khách hàng: '+data['name']+'</span><input type="hidden" id="customerID" name="customerID" value="'+data['customerID']+'" />').show();
                                                    document.getElementById("phone").setAttribute("readonly", "true");
                                                    document.getElementById("airline1").removeAttribute("readonly");
                                                    document.getElementById("booking_place_code1").removeAttribute("readonly");
                                                    document.getElementById("sumNet").removeAttribute("readonly");
                                                    document.getElementById("sumSale").removeAttribute("readonly");
                                                    $('button[type="button"]').removeAttr('disabled');
                                                    $('#booking_types1').removeAttr('disabled');
                                                    $("#airline1").focus();
//                                                    document.getElementById("customerID").value              = data['customerID'];
                                                }
                                            },
                                            error: function() 
                                            {
                                                
                                            }
                                    });
                        }, 1000);
                    }
            });

            $('#net_fare').autoNumeric('init',{aSign:' VNĐ',mDec:0, pSign:'s' });
            $('#sale_fare').autoNumeric('init',{aSign:' VNĐ',mDec:0, pSign:'s' });
            
            $("#airline1").blur(function() {
                document.getElementById("airline1").value       = $("#airline1").val().toUpperCase().replace(/\s/g, '');
            });
            
            $("#booking_place_code1").blur(function() {
                    var booking_types          = $("#booking_types1").val();
                    var airline                = $("#airline1").val().toUpperCase().replace(/\s/g, '');
                    var booking_place_code     = $("#booking_place_code1").val().toUpperCase().replace(/\s/g, '');
                    if(airline.length != 2){
                        alert("Vui lòng nhập hãng hàng không gồm 2 chữ số!");$("#airline1").focus();return false;
                    }
                    
                    if(booking_place_code == ""){
                        alert("<?php echo $this->lang->line('booking_place_code').' : '.$this->lang->line('require');?>");$("#booking_place_code1").focus();return false;
                    }
                    
                    setTimeout(function () {
                        $.ajax(
                                {
                                    url : '/auth/voucher/getInfoBookingHold',
                                    type: "POST",
                                    data : {booking_types:booking_types,airline:airline,booking_place_code:booking_place_code,customerID:$("#customerID").val()},
                                    cache: true,
                                    success:function(responseData) 
                                    {
                                        var data    = JSON.parse(responseData);
                                        switch(data['error']){
                                            case 0:
                                                var data1    = JSON.parse(data['msg']);
                                                
                                                document.getElementById("net_fare1").value                   = FormatNumber(data1.net_fare);
                                                document.getElementById("net_fare_fake1").value              = data1.net_fare;
                                                document.getElementById("sale_fare1").value                  = FormatNumber(data1.sale_fare);
                                                document.getElementById("sale_fare_fake1").value             = data1.sale_fare;
                                                document.getElementById("createdTime1").value                = data1.createdTime;

                                                document.getElementById("airline1").setAttribute("readonly", "true");
                                                document.getElementById("booking_place_code1").setAttribute("readonly", "true");
                                                break;
                                            case 1:
                                                document.getElementById("net_fare1").value                   = '';
                                                document.getElementById("net_fare_fake1").value              = '';
                                                document.getElementById("sale_fare1").value                  = '';
                                                document.getElementById("sale_fare_fake1").value             = '';
                                                
                                                alert("Không tìm thấy Code "+$("#booking_place_code1").val()+' - Hãng '+$("#airline1").val()+' đối với KH và booker này trên hệ thống booking hold');
                                                $("#airline1").focus();
                                                return false;
                                                break;
                                            case 2:
                                                document.getElementById("net_fare1").value                   = '';
                                                document.getElementById("net_fare_fake1").value              = '';
                                                document.getElementById("sale_fare1").value                  = '';
                                                document.getElementById("sale_fare_fake1").value             = '';
                                                
                                                var data1    = JSON.parse(data['msg']);
                                                alert("Code "+$("#booking_place_code1").val()+' - Hãng '+$("#airline1").val() + ' đã được tạo trong chứng từ số '+data1.id);
                                                $("#airline1").focus();                                
                                                return false;
                                                break;
                                        }
                                    },
                                    error: function() 
                                    {
                                        alert("Lỗi check code! Vui lòng liên hệ Admin");return false;
                                    }
                                });
                    }, 1000);
            });

            var input_add = <?php echo count($voucher->booking_info)+1?>;
            $("button.btn-success").on('click',function (e) {
                setTimeout(function () {
                    $.ajax({
                        url : '/auth/voucher/getInfoAirCode',
                        type: "POST",
                        data : {add: input_add},
                        cache: true,
                        success:function(data) 
                        {
                            $("#foneadd").append(data);
                            input_add = input_add + 1;
                        },
                        error: function() 
                        {
                            alert("Có lỗi xảy ra khi thêm dữ liệu! Liên hệ Admin!");return false;
                        }
                    });
                }, 111);
            });
            
            $('#sumNet').autoNumeric('init',{aSign:' VNĐ',mDec:0, pSign:'s' });
            $('#sumSale').autoNumeric('init',{aSign:' VNĐ',mDec:0, pSign:'s' });
            
            $( "#sumNet" ).on('click',function() {
                    //sumNet
                    var sumNet = 0;
                    $(".sumNet").each(function(){
                        sumNet = Number($(this).val()) + Number(sumNet);
                    });
                    document.getElementById("sumNet").value             = FormatNumber(sumNet);
                    document.getElementById("sumNet_fake").value        = sumNet;
                    $('#payment_method').removeAttr('disabled');
            });
            
            $( "#sumSale" ).on('click',function() {
                    //sumSale
                    var sumSale = 0;
                    $(".sumSale").each(function(){
                        sumSale = Number($(this).val()) + Number(sumSale);
                    });
                    document.getElementById("sumSale").value            = FormatNumber(sumSale);
                    document.getElementById("sumSale_fake").value       = sumSale;
                    $('#payment_method').removeAttr('disabled');
            });
            
            $( "#payment_method" ).change(function() {
                if($(this).val() == ""){
                    alert("Vui lòng chọn Phương thức thanh toán");return false;
                }
                if(url_segment == 'add'){
                    $("#note_bk").removeAttr('readonly');
                    $("#note_bk").focus();
                }
                $('button[type="submit"]').removeAttr('disabled');
                    updateURL = '/auth/booking/paymentMethod?id='+$(this).val()+'&cid='+$("#customerID").val();
                    $.ajax(
                    {
                            url : updateURL,
                            success:function(data)
                            {
                               $("#payment_method_form").html(data);
                            },
                            error: function() 
                            {
                                $("#simple-msg").html('Vui lòng liên hệ Admin!');
                            }
                    });
            });
            
            $("#foneadd").on('blur',function() {
                console.log(1111111);
//                    //sumSale
//                    var sumSale = 0;
//                    $(".sumSale").each(function(){
//                        sumSale = Number($(this).val()) + Number(sumSale);
//                    });
//                    document.getElementById("sumSale").value            = FormatNumber(sumSale);
//                    document.getElementById("sumSale_fake").value       = sumSale;
//                    $('#payment_method').removeAttr('disabled');
            });
});

function FormatNumber(x) {
    if (typeof x === "undefined") {
        return '';
    } else {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ' VNĐ';
    }
};
///,|VNĐ|\s/g
function UnFormatNumber(x) {
    if (typeof x === "undefined") {
        return '';
    } else {
    return x.toString().replace(/,|VNĐ|\s/g, "");
    }
};

function deleteRecord(input){
    if (confirm('Bạn chắc chắn muốn xóa?')) {
       // delete it!
       var value    = input.value;
       var sumNet   = $("#sumNet_fake").val() - $("#net_fare_fake"+value).val();
       var sumSale  = $("#sumSale_fake").val() - $("#sale_fare_fake"+value).val();
       document.getElementById("sumNet").value             = FormatNumber(sumNet);
       document.getElementById("sumNet_fake").value        = sumNet;
       document.getElementById("sumSale").value            = FormatNumber(sumSale);
       document.getElementById("sumSale_fake").value       = sumSale;
       
       $(input).parent().remove();
    } else {
        // Do nothing!
    }
}
</script>